<template>
  <div class="app-container sjdc flex-row-between" v-loading="loading" element-loading-text="拼命加载中">
    <div class="left">
      <p class="sjxz_p">时间选择</p>
      <div>
        <el-radio-group v-model="radio" @change="handleChangeGroup" style="width: 100%">
          <el-radio :label="3">快捷筛选</el-radio>
          <el-radio :label="6">自定义</el-radio>
        </el-radio-group>
      </div>
      <div style="margin-top: 14.5px">
        <el-select size="mini" placeholder="请选择" v-model="seval" style="width: 100%" :disabled="radio == 6"
          @change="handleSelectTimeChange" clearable>
          <el-option v-for="item in timeDataList" :label="item.label" :value="item.value" :key="item.value"></el-option>
        </el-select>
      </div>
      <!-- <p class="sjxz_p" style="margin-top: 20px">时间选择</p> -->
      <div style="margin-top: 14.5px">
        <el-date-picker size="mini" @change="handleDatePickerChange" :disabled="radio == 3" :editable="false" style="width: 100%;"
          v-model="dataTime" :picker-options="options" unlink-panels format="yyyy-MM-dd HH:mm" type="datetimerange"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>

        <!-- <el-date-picker
          :disabled="radio == 3"
          size="mini"
          style="width: 100%"
          v-model="dataTime"
          type="daterange"
          clearable
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
        ></el-date-picker>-->
      </div>
      <div>
        <el-tabs v-model="uuid" stretch @tab-click="handleClick">
          <el-tab-pane v-for="item in DTUList" :key="item.uuid" :label="item.name" :name="item.uuid">
            <span slot="label">{{item.name}}</span>
            <div>
              <div style="margin: 15px 0" class="flex-between">
                <el-select @change="handleChange" size="mini" v-model="one" clearable filterable style="width: 240px;">
                  <el-option v-for="item in dataList" :label="item.rtuIndex" :value="item.rtuIndex"
                    :key="item"></el-option>
                </el-select>
                <span style="color: #409eff; font-size: 14px;cursor: pointer;" @click="handleReset">重置</span>
              </div>
              <div class="box_table">
                <el-table ref="multipleTable" height="calc(100vh - 410px)" @selection-change="handleSelectionChange"
                  @select-all="handleSelectAll" :data="filterTableData" :row-key="rowKey" style="width: 100%"
                  :cell-style="{ textAlign: 'center' }" :header-cell-style="{
                    background: 'rgba(250, 250, 250, 1)',
                    textAlign: 'center',
                  }">
                  <el-table-column type="selection" style="width: 50px;" :reserve-selection="true" />
                  <!-- <el-table-column label="传感器名称" prop="name" /> -->
                  <!-- <el-table-column label="传感器名称">
                    <template slot-scope="scope">{{`${scope.row.parentName}-${scope.row.name}`}}</template>
                  </el-table-column>-->
                  <el-table-column label="传感器名称">
                    <template slot-scope="scope">{{`${scope.row.rtuIndex}：${scope.row.rtuName}`}}</template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="right">
      <!-- <div class="kb_cont" ref="kb_zx"></div> -->
      <div class="kb_cont">
        <One v-if="isShow == 1" />
        <Two v-else-if="isShow == 2" />
        <Three v-else-if="isShow == 3" />
        <!-- <HistoryData v-if="isShow" :titArr="echartsTitleArr" /> -->
        <div v-else class="currently_div">暂无数据</div>
      </div>
      <div class="table_div table_div2">
        <el-divider content-position="center">阈值参考表</el-divider>
        <!-- <div
          style="
            font-size: 14px;
            color: rgba(56, 56, 56, 1);
            padding: 15px 0;
          "
        >阈值参考表</div>-->
        <el-table hover-row="false" height="calc(100vh - 745px)" :data="tableData" style="width: 100%"
          :cell-style="{ textAlign: 'center' }" :header-cell-style="{
            background: 'rgba(250, 250, 250, 1)',
            textAlign: 'center'
          }">
          <!-- <el-table-column prop="name" label="传感器名称" /> -->
          <el-table-column label="传感器名称">
            <template slot-scope="scope">{{`${scope.row.rtuIndex}：${scope.row.rtuName}`}}</template>
          </el-table-column>
          <el-table-column prop="measuringThreshold.totalRange" label="总量程" />
          <el-table-column prop="measuringThreshold.thresholdPositive" label="正向量程" />
          <el-table-column prop="measuringThreshold.thresholdNegative" label="反向量程" />
          <el-table-column prop="measuringThreshold.warningPositive" label="正向阈值" />
          <el-table-column prop="measuringThreshold.warningNegative" label="反向阈值" />
        </el-table>
        <!-- <div class="fenye_div">
              <el-pagination
                background
                :current-page="currentPage4"
                :page-sizes="[100, 200, 300, 400]"
                :page-size="100"
                layout="total, sizes, prev, pager, next, jumper"
                :total="400"
              />
        </div>-->
      </div>
    </div>
  </div>
</template>

<script>
  import HistoryData from "@/components/HistoryData";

  import One from "@/components/One";
  import Two from "@/components/Two";
  import Three from "@/components/Three";
  import { getManagerDTUInfo, getManagerDTUOnlineStatus } from "@/api/manager";
  import { realTimeData, dataChartData } from "@/api/data";

  export default {
    components: {
      One,
      Two,
      Three,
      HistoryData
    },
    data() {
      return {
        lock: true,
        oldUuid: "",
        loading: false,
        dataList: [],
        uuid: "",
        DTUOnlineList: [],
        DTUList: [],
        selectDate: "",
        // options: {
        //   // 时间不能大于当前时间
        //   disabledDate: time => {
        //     return time.getTime() > Date.now();
        //   },
        //   selectableRange: "00:00:00 - 23:59:59"
        // },
        options: {
          onPick: ({ maxDate, minDate }) => {
            this.selectDate = minDate.getTime();
            if (maxDate) {
              this.selectDate = "";
            }
          },
          disabledDate: (time) => {
            if (this.selectDate !== "") {
              const one = 30 * 24 * 3600 * 1000;
              const minTime = this.selectDate - one;
              const maxTime = this.selectDate + one;
              return time.getTime() < minTime || time.getTime() > maxTime;
            }
            return time.getTime() > Date.now();
          },
          selectableRange: "00:00:00 - 23:59:59"
        },
        isShow: false,
        echartsTitleArr: [],
        multiSelectedGroups: [],
        seval: "",
        activeName: "first",
        one: "",
        two: "",
        timeDataList: [
          {
            label: "最近1周",
            value: "week"
          },
          {
            label: "最近1个月",
            value: "oneMonth"
          },
          // {
          //   label: "最近2个月",
          //   value: "twoMonth"
          // },
          // {
          //   label: "最近3个月",
          //   value: "threeMonth"
          // }
        ],
        radio: 3,
        dataTime: [],
        tableData: [],
        filterTableData: []
      };
    },
    created() {
      // this.echartsTitleArr.push(
      //   this.tableData1[0].name,
      //   this.tableData1[1].name,
      //   this.tableData1[2].name
      // );
      this.handleClick();

      // 获取DTU
      this.getManagerDTUOnlineStatus();
    },
    watch: {
      isShow(val) {
        if (!val) {
          const idx = this.DTUList.findIndex(item => item.uuid == this.uuid);
          this.$refs.multipleTable[idx].clearSelection();
        }
      },
      echartsTitleArr: {
        handler(list) {
          if (list.length == 0) {
            this.isShow = false;
            return;
          }
          if (list.length > 0) {
            if (this.seval || this.dataTime.length) {
              if (list.length == 1) {
                this.isShow = 1;
              } else if (list.length == 2) {
                this.isShow = 2;
              } else if (list.length == 3) {
                this.isShow = 3;
              }
            } else {
              this.$message("请先选择时间");
              this.$refs.multipleTable1[0].clearSelection();
            }
          }
        },
        immediate: true
      }
    },
    methods: {
      resetTableSelection() {
        const idx = this.DTUList.findIndex(item => item.uuid == this.uuid);
        this.$refs.multipleTable[idx].clearSelection();
        this.isShow = false;
        localStorage.setItem("timeType", false);
      },
      async realTimeData() {
        try {
          this.loading = true;
          const { code, result: { data }, message } = await realTimeData({
            dtuUuid: this.uuid,
            rtuOnline: true
          });
          if (code == 0) {
            this.dataList = JSON.parse(JSON.stringify(data));
            this.dataList.sort((firstItem, secondItem) => firstItem.rtuIndex - secondItem.rtuIndex);
            this.filterTableData = JSON.parse(JSON.stringify(this.dataList));
            this.loading = false;
          }
        } catch (err) {
          console.log("调用接口报错了获取RTU", err);
        }
      },
      // 获取DTU在线状态
      async getManagerDTUOnlineStatus() {
        try {
          const { result, message, code } = await getManagerDTUOnlineStatus();
          if (code == 0) {
            this.DTUOnlineList = result.filter(item => item.online);
            this.uuid = this.DTUOnlineList[0].uuid;
            console.log("uuid", this.uuid);
            await this.getManagerDTUInfo();
          }
        } catch (err) {
          this.loading = false;
          console.log("调用接口报错了DTU在线状态", err);
        }
      },
      // 获取全部DTU信息
      async getManagerDTUInfo() {
        try {
          const { result: { data }, message, code } = await getManagerDTUInfo();
          const list = [];
          if (code == 0) {
            for (let i = 0; i < this.DTUOnlineList.length; i++) {
              const onLineUuid = this.DTUOnlineList[i].uuid;
              for (let j = 0; j < data.length; j++) {
                if (data[j].uuid == onLineUuid) {
                  list.push(data[j]);
                }
              }
            }
            this.DTUList = JSON.parse(JSON.stringify(list));
            this.handleClick();
          }
        } catch (err) {
          this.loading = false;
          console.log("调用接口报错了全部DTU", err);
        }
      },
      handleSelectTimeChange(type) {
        try {
          this.resetTableSelection();
        } catch (error) {
          console.log("取消表格勾选", error);
        }
        if (this.seval && this.echartsTitleArr.length) {
          this.isShow = true;
        }
        localStorage.setItem("timeType", type);
        localStorage.setItem("historyTimeType", 1);
      },
      handleDatePickerChange() {
        this.resetTableSelection();
        if (this.dataTime.length && this.echartsTitleArr.length) {
          this.isShow = true;
        }
        const startTimeInSecond = new Date(this.dataTime[0]).getTime() / 1000;
        const endTimeInSecond = new Date(this.dataTime[1]).getTime() / 1000;
        localStorage.setItem("startTimeInSecond", startTimeInSecond);
        localStorage.setItem("endTimeInSecond", endTimeInSecond);
        localStorage.setItem("historyTimeType", 2);
      },
      handleSelectAll() {
        if (this.activeName == "first") {
          this.$refs.multipleTable1.clearSelection();
        } else {
          this.$refs.multipleTable2.clearSelection();
        }
      },
      rowKey(row) {
        return row.id;
      },
      handleSelectionChange(list) {
        if (this.seval.length > 0 || this.dataTime.length > 0) {
          this.lock = true;
          if (list.length > 3) {
            this.limitFn(list);
            return;
          }
          this.multiSelectedGroups = [...list];
          this.tableData = [...list];
          this.echartsTitleArr = list.map(item => item.name);
          const rtuIndexList = list.map(item => item.rtuIndex);
          console.log("rtuIndexList", rtuIndexList);

          // 存储uuid和RTU索引和RTU名字
          localStorage.setItem("historyRtuIndexList", JSON.stringify(rtuIndexList));
          localStorage.setItem("historyUuid", JSON.stringify(this.uuid));
          localStorage.setItem("historyTitArr", JSON.stringify(this.echartsTitleArr));
        } else {
          this.$nextTick(() => {
            const idx = this.DTUList.findIndex(item => item.uuid == this.uuid);
            this.$refs.multipleTable[idx].clearSelection();
            if (this.lock) {
              this.$message("请先选择时间");
            }
            this.lock = false;
          });
        }
      },
      // 限制数量方法
      limitFn(list) {
        const idx = this.DTUList.findIndex(item => item.uuid == this.uuid);
        this.$refs.multipleTable[idx].clearSelection(); //用于多选表格，清空用户的选择
        for (let i = 0; i < 3; i++) {
          this.$refs.multipleTable[idx].toggleRowSelection(list[i]); //用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        }
      },
      handleReset() {
        this.one = this.two = "";
        this.filterTableData = JSON.parse(JSON.stringify(this.dataList));
      },
      handleChange() {
        this.filterTableData = JSON.parse(JSON.stringify(this.dataList.filter(item => item.rtuIndex == this.one)));
      },
      handleClick() {
        if (this.oldUuid != this.uuid) {
          this.isShow = 0;
          this.oldUuid = this.uuid;
          this.one = this.two = "";
          const idx = this.DTUList.findIndex(item => item.uuid == this.uuid);
          this.$refs.multipleTable && this.$refs.multipleTable[idx].clearSelection();
          this.realTimeData();
        }
      },
      handleChangeGroup() {
        this.seval = "";
        this.dataTime = [];
      }
    }
  };
</script>

<style lang="scss">
  .sjdc {

    /* 取消表格全选勾选给框 */
    .el-table__header-wrapper .el-checkbox {
      display: none !important;
    }

    .fenye_div {
      margin-top: 30px;
      text-align: right;
    }

    .tit_p_1 {
      /** 文本1 */
      font-size: 14px;
      font-weight: 400;
      color: rgba(166, 166, 166, 1);
      margin-left: 30px;
    }

    .kb_cont {
      width: 100%;
      height: 500px;
      background-color: #fff;
      margin-top: 20px;
      padding-top: 20px;
      padding-bottom: 20px;
    }

    .dot_div {
      width: 15px;
      height: 15px;
      background: rgba(24, 144, 255, 1);
      border-radius: 50%;
      border: 1px solid rgba(255, 255, 255, 0.85);
    }

    .el-tabs__nav-wrap::after {
      background-color: transparent;
    }

    .el-radio-group {
      display: flex;
      justify-content: space-between;
      box-sizing: border-box;
      padding-left: 10px;
      padding-right: 10px;
    }

    .left,
    .right {
      height: 100%;
      background-color: #fff;
      padding: 20px;
      box-sizing: border-box;
    }

    .left {
      width: 20%;
      padding: 20px;
      box-sizing: border-box;

      .sjxz_p {
        font-size: 14px;
        margin-top: 0;
        color: rgba(56, 56, 56, 1);
      }
    }

    .right {
      width: 78.8%;
    }
  }

  .box_table {

    .el-table td,
    .el-table th.is-leaf {
      border: 0;
    }
  }

  .table_div2 {
    .el-table--enable-row-hover .el-table__body tr:hover>td {
      background-color: white !important;
    }
  }

  .currently_div {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>